<template>
    <main class="content">
        <!-- 医生信息表格 -->
        <div class="table-header">
            <span>医生信息</span>
            <el-button class="exportButton" style="float: right; padding: 3px 0" size="small" @click="exportDoctorInfo">
                导出报告
            </el-button>
        </div>
        <el-card class="box-card">
            <div class="table-container" style="width: 800px; float:left;" >
                <el-table :data="doctorData" stripe style="width: 100%" id="doctorPdf">
                    <el-table-column prop="id" label="医生编号" width="200"></el-table-column>
                    <el-table-column prop="name" label="姓名" width="200"></el-table-column>
                    <el-table-column prop="visits" label="接诊数量" width="200"></el-table-column>
                    <el-table-column prop="hours" label="工作小时"></el-table-column>
                </el-table>
            </div>
            <div ref="chartDom" style="width: 525px; height: 350px; float:right;"></div>
        </el-card>

        <!-- 预约和就诊数据表格 -->
        <div class="table-header">
            <span style="margin-right: 20px;">预约和就诊数据</span>
            <el-button-group class="button-group">
                <el-button
                    class="chooseButton"
                    :class="{ 'active': activeButton === 'all' }"
                    type="primary"
                    @click="handleOption(null)"
                >全部</el-button>
                <el-button
                    class="chooseButton"
                    :class="{ 'active': activeButton === 'finished' }"
                    type="primary"
                    @click="handleOption('是')"
                >已完成</el-button>
                <el-button
                    class="chooseButton"
                    :class="{ 'active': activeButton === 'unfinished' }"
                    type="primary"
                    @click="handleOption('否')"
                >未完成</el-button>
            </el-button-group>
            <el-button class="chooseButton" style=" padding: 3px 0; margin-left: 10px;" @click="getBookDatas">
                刷新
            </el-button>
            <el-button class="exportButton" style="float: right; padding: 3px 0" size="small" @click="exportBookInfo">
                导出报告
            </el-button>
        </div>
        <el-card class="box-card" style="margin-top: 20px;">
            <div class="table-container" style="width: 1000px; float:left;">
                <el-table :data="bookData" stripe style="width: 100%" id="bookPdf">
                    <el-table-column prop="bookId" label="预约编号" width="150"></el-table-column>
                    <el-table-column prop="time" label="时间" width="200"></el-table-column>
                    <el-table-column prop="doctorId" label="医生编号" width="150"></el-table-column>
                    <el-table-column prop="doctorName" label="医生姓名" width="150"></el-table-column>
                    <el-table-column prop="patientName" label="病人姓名" width="150"></el-table-column>
                    <el-table-column prop="status" label="完成情况"></el-table-column>
                </el-table>
            </div>
            <div ref="pieChartDom" style="width: 300px; height: 300px; float:right;"></div>
        </el-card>
    </main>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import * as echarts from 'echarts';

import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
    name: 'StatisticPage',
    setup() {
        const doctorData = ref([
            { id: '01', name: '王小二', visits: 100, hours: 50 },
            { id: '02', name: '李大三', visits: 200, hours: 100 },
            { id: '03', name: '张四', visits: 300, hours: 150 },
            { id: '03', name: '张四', visits: 300, hours: 150 },
            { id: '03', name: '张四', visits: 300, hours: 150 },
            { id: '03', name: '张四', visits: 300, hours: 150 },
            { id: '03', name: '张四', visits: 300, hours: 150 },
            { id: '03', name: '张四', visits: 300, hours: 150 }
        ]);

        const intervalCount = 5;  // 直方图区间数

        const histogramData = computed(() => {
            const visitsArray = doctorData.value.map(item => item.visits);
            const maxVisits = Math.max(...visitsArray);
            const minVisits = Math.min(...visitsArray);
            const intervalSize = Math.ceil((maxVisits - minVisits + 1) / intervalCount);

            const histogram = new Array(intervalCount).fill(0);
            visitsArray.forEach(visits => {
                const intervalIndex = Math.floor((visits - minVisits) / intervalSize);
                histogram[intervalIndex]++;
            });
            return histogram;
        });

        const transformBookingData = (data) => {
            return data.map(item => ({
                bookId: item.bookId.toString().padStart(2, '0'),
                time: item.time,
                doctorId: item.doctorId,
                doctorName: item.doctorName,
                patientName: item.patientName,
                status: item.status
            }));
        };

        const getBookDatas = async () => {
            console.log("获取预约记录");
            await axios.post('http://localhost:8085/booking', {
                status: activeButton.value })
                .then(response => {
                    if (response.status === 200) {
                        console.log(response.data);
                        // 将返回的数据赋值给 scheduleData
                        bookData.value = transformBookingData(response.data);
                        updatePieChart();
                    } else {
                        // 显示错误消息
                        ElMessage({
                            type: 'error',
                            message: '获取排班失败，请重试',
                        });
                    }
                })
                .catch((error) => {
                    // 捕获错误并显示错误消息
                    console.error('请求错误:', error);
                    ElMessage({
                        type: 'error',
                        message: '获取排班失败，请重试',
                    });
                });
        }

        const bookData = ref(null);
        const activeButton = ref(null);

        const chartDom = ref(null);
        let chart = null;

        const pieChartDom = ref(null);
        let pieChart = null;

        getBookDatas();
        console.log(bookData.value);

        const exportDoctorInfo = () => {
            console.log("导出医生信息报告");
            exportToPDF(document.querySelector('#doctorPdf'), '医生信息报告.pdf');
        };

        const exportBookInfo = () => {
            console.log("导出预约记录报告");
            exportToPDF(document.querySelector('#bookPdf'), '预约记录报告.pdf');
        };

        const handleOption = (option) => {
            activeButton.value = option;
            console.log("选择展示");
            getBookDatas();
        };

        const exportToPDF = (element, filename) => {

            const margin = 10;

            html2canvas(element, { scrollY: -window.scrollY }).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const pdf = new jsPDF('p', 'pt', 'a4');
                const pdfWidth = pdf.internal.pageSize.getWidth() - margin * 2;
                const pdfHeight = pdf.internal.pageSize.getHeight() - margin * 2;
                const imgProps = pdf.getImageProperties(imgData);
                const imgWidth = pdfWidth;
                const imgHeight = (imgProps.height * imgWidth) / imgProps.width;
                let adjustedImgHeight = imgHeight;
                let adjustedImgWidth = imgWidth;
                if (imgHeight > pdfHeight) {
                    adjustedImgHeight = pdfHeight;
                    adjustedImgWidth = (imgProps.width * adjustedImgHeight) / imgProps.height;
                }

                let heightLeft = adjustedImgHeight;
                let position = margin; // 从边缘开始

                // 添加第一页
                pdf.addImage(imgData, 'PNG', margin + (pdfWidth - adjustedImgWidth) / 2, position, adjustedImgWidth, adjustedImgHeight);
                heightLeft -= pdfHeight;

                // 如有需要，添加更多页面
                while (heightLeft > 0) {
                    position = heightLeft - adjustedImgHeight + margin; // 从边缘开始
                    pdf.addPage();
                    pdf.addImage(imgData, 'PNG', margin + (pdfWidth - adjustedImgWidth) / 2, position, adjustedImgWidth, adjustedImgHeight);
                    heightLeft -= pdfHeight;
                }

                pdf.save(filename);
            });
        };


        const updateChart = () => {
            if (chart) {
                const option = {
                    title: {
                        text: '接诊数量直方图'
                    },
                    tooltip: {},
                    xAxis: {
                        type: 'category',
                        data: Array.from({ length: intervalCount }, (_, i) => {
                            const minVisits = Math.min(...doctorData.value.map(item => item.visits));
                            const intervalSize = Math.ceil((Math.max(...doctorData.value.map(item => item.visits)) - minVisits + 1) / intervalCount);
                            return `${minVisits + i * intervalSize}-${minVisits + (i + 1) * intervalSize - 1}`;
                        })
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        name: '医生人数',
                        type: 'bar',
                        data: histogramData.value
                    }]
                };

                chart.setOption(option);
            }
        };

        const updatePieChart = () => {
            if (pieChart) {
                const statusCounts = bookData.value.reduce((acc, item) => {
                    acc[item.status] = (acc[item.status] || 0) + 1;
                    return acc;
                }, {});

                const pieChartData = Object.keys(statusCounts).map(key => ({
                    name: key,
                    value: statusCounts[key]
                }));

                pieChart.setOption({
                    title: {
                        text: '预约完成统计',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        bottom: '10',
                        left: 'center'
                    },
                    series: [
                        {
                            name: '完成状态',
                            type: 'pie',
                            radius: '50%',
                            data: pieChartData,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                });
            }
        };

        console.log("2222", bookData.value);


        onMounted(() => {
            chart = echarts.init(chartDom.value);
            updateChart();
            pieChart = echarts.init(pieChartDom.value);
        });

        watch(histogramData, () => {
            updateChart();
        });


        return {
            activeButton,
            doctorData,
            bookData,
            chartDom,
            pieChartDom,
            getBookDatas,
            exportDoctorInfo,
            exportBookInfo,
            handleOption,
            exportToPDF
        }
    }
};
</script>

<style scoped>

.exportButton {
    width: 60px;
    height: 30px;
    margin-right: 20px;
    background-color: darkgray;
    color: white;
}

.exportButton:hover {
    width: 70px;
    height: 35px;
}

.content {
    flex: 1; /* 让内容部分占据剩余空间 */
    padding: 1%;
}

.box-card {
    margin: 20px;
    height: 350px;    /* 设置卡片的固定高度 */
    overflow: hidden; /* 隐藏溢出的内容 */
}

.table-container {
    max-height: 300px; /* 设置最大高度 */
    overflow-y: auto;  /* 使内容可滚动 */
}

.table-header {
    text-align: left;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;       /* 与下方表格的距离 */
}

.chooseButton {
    background-color: lightgray;
    color: gray;
    width: 60px;
}

.chooseButton:hover {
    background-color: darkgray; /* 鼠标悬浮时的背景色 */
    color: white;
}

.chooseButton.active {
    background-color: darkgray;
    color: white;
}

.button-group {
    border: white; /* 边框颜色 */
}

.button-group .el-button {
    border-color: white; /* 调整按钮组内部按钮的边框颜色 */
}


</style>
